//引入数据库连接
const conn = require('../db/db.js');
const showIndex = (req,res) => {
    //写sql语句
    let sql = `select a.id,a.title,a.ctime,u.nickname from blog_articles a
    left join blog_users u on a.authorId=u.id
    order by a.ctime desc
    limit 3`;
    conn.query(sql,(err,result) => {
        if(err) return res.send('出错了');
        if(result.length == 0) return res.send('没有数据');
        res.render('index.ejs',{
            "user":req.session.user,
            "islogin":req.session.islogin,
            "articles":result
        });
    })
   
}
//分页
const pagination = (req,res) => {
    let currentPage = req.body.currentPage;
    let pageSize = req.body.pageSize;
    let startPage = (currentPage - 1) * pageSize;
    //写sql语句
    let sql = `select a.id,a.title,a.ctime,u.nickname ,(select count(*) from blog_articles) as total from blog_articles a
    left join blog_users u on a.authorId=u.id
    order by a.ctime desc
    limit ${startPage},${pageSize}`;
    conn.query(sql,(err,result) => {
        if(err) return res.send('出错了');
        if(result.length == 0) return res.send('没有数据');
        let totalPage = Math.ceil(result[0].total / pageSize);  
        // console.log(result);
        // res.render('index.ejs',{
        //     "user":req.session.user,
        //     "islogin":req.session.islogin,
        //     "articles":result
        // });
        res.send({status:200,message:'操作成功',totalPage:totalPage,data:result});        
    })
   
}
//导出showIndex
module.exports = {
    showIndex,
    pagination
}